package com.douqu.game.core.util;

import com.alibaba.fastjson.JSONObject;
import com.bean.core.util.HttpJsonUtils;
import com.bean.core.util.MD5Utils;
import com.bean.core.util.TimeUtils;
import com.bean.core.util.Utils;
import com.douqu.game.core.entity.ext.data.timeLimit.TimePropDB;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.HttpFactory;
import com.douqu.game.core.web.RechargeCallBackParam;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2018-08-24 17:28
 */
public class PayUtils {


    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(JSONObject params, boolean isSort, String... splits)
    {
        String split = splits.length == 0 ? "" : splits[0];
        List<String> keys = new ArrayList<String>(params.keySet());
        if(isSort)
            Collections.sort(keys);

        String prestr = "";
        String key = "";
        Object value;
        for (int i = 0; i < keys.size(); i++) {
            key = keys.get(i);
            value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + split;
            }
        }

        return prestr;
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, Object> params, String... splits)
    {
        String split = splits.length == 0 ? "" : splits[0];
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String prestr = "";
        String key = "";
        Object value;
        for (int i = 0; i < keys.size(); i++) {
            key = keys.get(i);
            value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + split;
            }
        }

        return prestr;
    }

    public static String quicksdkDecode(String src, String key) {
        if(src == null || src.length() == 0){
            return src;
        }
        Pattern pattern = Pattern.compile("\\d+");
        Matcher m = pattern.matcher(src);
        List<Integer> list = new ArrayList();
        while (m.find()) {
            try {
                String group = m.group();
                list.add(Integer.valueOf(group));
            } catch (Exception e) {
                e.printStackTrace();
                return src;
            }
        }
        if (list.size() > 0) {
            try {
                byte[] data = new byte[list.size()];
                byte[] keys = key.getBytes();
                for (int i = 0; i < data.length; i++) {
                    data[i] = (byte) (list.get(i) - (0xff & keys[i % keys.length]));
                }
                return new String(data, "UTF-8");
            } catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            return src;
        } else {
            return src;
        }
    }

    public static boolean checkOrderFromMainServer(String url, int serverId, String playerIndex, String rechargeParam, String outTradeNo, String platformTradeNo, int fee, String payType, String channel, boolean isTest)
    {
        String checkString = serverId + ConstantFactory.RECHARGE_KEY + TimeUtils.getCurrentTime(TimeUtils.YYYYMMDD);
        RechargeCallBackParam param = new RechargeCallBackParam();
        param.setObjectIndex(playerIndex);
        param.setRechargeParam(rechargeParam);
        param.setOutTradeNo(outTradeNo);
        param.setTcd(platformTradeNo);
        param.setFee(fee);
        param.setChannel(channel);
        param.setPayType(payType);
        param.setTest(isTest?1:0);
        param.setPassword(MD5Utils.encodeUppercase(checkString));

        return checkOrderFromMainServer(url, param);
    }

    public static boolean checkOrderFromMainServer(String url, RechargeCallBackParam callBackParam)
    {
        JSONObject result = HttpJsonUtils.httpPost(url + HttpFactory.ORDER_CHECK, callBackParam.toJSONObject());
        LogUtils.warn(callBackParam.getOutTradeNo() + "  冲值验证返回 -> " + result);
        try{
            return result != null && Integer.parseInt(result.getString("code")) == 0;
        }catch (Exception e){
            LogUtils.errorException(e);
            return false;
        }
    }


    public static String getEnumType(String enumName)
    {
        return enumName.substring(enumName.lastIndexOf("_")+1, enumName.length());
    }


    public static boolean isNullOrEmpty(String... params)
    {
        for(String param : params)
        {
            if(Utils.isNullOrEmpty(param))
                return true;
        }
        return false;
    }
    /**
     * 生成充值本地订单 保证唯一性
     *
     * @return
     */
    public static String createOutTradeNo(String platform)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(platform);
        sb.append(TimeUtils.getCurrentTime(TimeUtils.YYYYMMDDHHMMSS));
        sb.append(CoreUtils.createUUID(4));
        return sb.toString().toUpperCase();
    }


    /**
     *
     * @param objectIndex 玩家ID
     * @param rechargeId 冲值ID
     * @param serverId 服务器ID
     * @param lv 玩家等级
     * @param diamond 冲值钻石
     * @param serverRuleId 玩家来自哪个包
     * @param timeProp 时效性道具
     * @param clientParam 客户端需要的参数,目前只有支付宝有
     * @param outTradeNo 本地唯一订单号
     * @return
     */
    public static String createRechargeParam(String objectIndex, int rechargeId, int serverId, int lv, int diamond, int serverRuleId, TimePropDB timeProp, String clientParam, String outTradeNo)
    {
        return CoreUtils.concat(
                objectIndex,
                ConstantFactory.UNDERLINE,
                //iapID
                rechargeId,
                ConstantFactory.UNDERLINE,
                //gameServer
                serverId,
                ConstantFactory.UNDERLINE,
                //用户等级
                lv,
                ConstantFactory.UNDERLINE,
                diamond,
                ConstantFactory.UNDERLINE,
                serverRuleId,
                ConstantFactory.UNDERLINE,
                timeProp == null ? ConstantFactory.PLACEHOLDER : timeProp.uniqueId,
                ConstantFactory.UNDERLINE,
                Utils.isNullOrEmpty(clientParam) ? ConstantFactory.PLACEHOLDER : clientParam,
                ConstantFactory.UNDERLINE,
                outTradeNo);
    }


}
